// pages/orderDetail/orderDetail.js
import Dialog from '@vant/weapp/dialog/dialog';
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    isIphoneX: app.globalData.isIphoneX,
    id: '', // 订单id
    risk: '', // 分享文案
    show1: false,
    show2: false,
    orderDetail: '', // 订单详情
    expressList: [], // 物流信息
    batchShopList: [], // 批量列表
    batchType: '', // 批量操作类型 1-购买 2-取消
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    this.setData({
      id: options.id
    })
    this.getRisk()
  },

  // 跳转物流
  toLogistics() {
    wx.navigateTo({
      url: `/pages/logistics/logistics?expressNo=${this.data.orderDetail.expressNo}`,
    })
  },

  // 获取订单详情
  getDetail() {
    wx.showLoading({
      mask: true
    })
    wx.get(`${wx.api.malldetails}${this.data.id}`, res => {
      console.log('==== getDetail ===', res)
      wx.hideLoading()
      if (res.code == 200) {
        res.data.specificationsText = res.data.orderGoods[0].specifications.join('+')
        this.setData({
          orderDetail: res.data
        })
        if (res.data.expressNo) {
          wx.get(`${wx.api.mallqueryExpress}?expressNo=${res.data.expressNo}`, res => {
            console.log('==== queryExpress ===', res)
            if (res.code == 200) {
              this.setData({
                expressList: res.data.list
              })
            }
          }, fail => {})
        }
      }
    })
  },

  // 复制文案
  copyText(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.no,
      success(ress) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },

  // 立即支付
  repay() {
    wx.showLoading({
      mask: true
    }) 
    let batchNo = this.data.orderDetail.batchNo
    if (batchNo) { // 批量支付
      wx.get(`${wx.api.mallBatchOrder}?batchNo=${batchNo}`, res => {
        wx.hideLoading()
        console.log('==== batchOrder ===', res)
        if (res.code == 200) {
          this.setData({
            show3: true,
            batchShopList: res.data,
            batchType: '1'
          })
        }
      }, fail => {})
    } else {
      wx.post(wx.api.mallprepay, {orderNos:[this.data.orderDetail.orderNo]}, result => {
        console.log('==== prepay ===', result)
        wx.hideLoading()
        if (result.code == 200) {
          this.doWxPay(result)
        }
      })
    }
  },

  // 批量弹框
  sureCoupon() {
    if (this.data.batchType == '1') { // 批量购买
      let orderNos = []
      for (let index = 0; index < this.data.batchShopList.length; index++) {
        orderNos.push(this.data.batchShopList[index].orderNo)
      }
      console.info('==== orderNos ====', orderNos)
      wx.post(wx.api.mallprepay, {orderNos}, result => {
        console.log('==== prepay ===', result)
        wx.hideLoading()
        if (result.code == 200) {
          this.doWxPay(result)
        }
      })
    } else { // 批量取消
      this.cancelOrderMore()
    }
  },

  // 小程序发起微信支付
  doWxPay(param) {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.requestPayment({
      timeStamp: param.data.timeStamp, //记住，这边的timeStamp一定要是字符串类型的，不然会报错
      nonceStr: param.data.nonceStr,
      package: param.data.package,
      signType: param.data.signType,
      paySign: param.data.paySign,
      success(event) {
        console.log('==== success ====', event);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail(error) {
        console.log('==== error ====', error)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        });
      },
      complete() {
        wx.hideLoading()
        console.log("pay complete")
        that.setData({
          show3: false
        })
        that.getDetail()
      }
    });
  },

  // 申请售后
  toAfter(e) {
    wx.setStorage({
      key: "afterDetail",
      data: e.currentTarget.dataset.item,
      success() {
        wx.navigateTo({
          url: '/pages/shopAfterSales/afterSales?type=2'
        })
      }
    })
  },

  // 修改地址
  setAddress(e) {
    wx.navigateTo({
      url: `../addressList/addressList?fromType=setAddress&id=${e.currentTarget.dataset.id}`
    })
  },

  // 删除订单
  delOrder(e) {
    Dialog.confirm({
        title: '温馨提示',
        message: '是否删除该订单',
      })
      .then(() => {
        // on confirm
        wx.get(`${wx.api.malldelete}${e.currentTarget.dataset.id}`, res => {
          console.log('==== deleteOrder ===', res)
          if (res.code == 200) {
            wx.showToast({
              icon: 'none',
              title: '暂无更多数据'
            })
            wx.navigateBack({
              delta: 1
            })
          }
        }, fail => {})
      })
      .catch(() => {
        // on cancel
      });
  },

  // 删除记录
  delSaleOrder(e) {
    let that = this
    Dialog.confirm({
        title: '温馨提示',
        message: '是否删除该记录',
      })
      .then(() => {
        // on confirm
        wx.get(`/api/sales/delete/${e.currentTarget.dataset.id}`, res => {
          console.log('==== deleteOrder ===', res)
          if (res.code == 200) {
            wx.showToast({
              icon: 'none',
              title: '暂无更多数据'
            })
            var pages = getCurrentPages();
            if(pages.length > 1){
                var prePage = pages[pages.length - 2];
                prePage.refreshOrdrList()
            }
            wx.navigateBack({
              delta: 1
            })
          }
        }, fail => {})
      })
      .catch(() => {
        // on cancel
      });
  },
  
  // 取消订单
  cancelOrder(e) {
    let that = this
    let text
    if (e.currentTarget.dataset.orderstatus == 0) {
      text = '订单状况变化可能有延迟，如您已经付款，请稍等一段时间。请确认是否未付款并且不需要本商品？'
    } else {
      text = '选择退订退款后，订单将取消，退款将于10-30分钟内退回到您的支付账户。请确认是否退订退款？'
    }
    Dialog.confirm({
        title: '温馨提示',
        message: text,
      })
      .then(() => {
        // on confirm
        wx.showLoading({
          mask: true
        })
        let batchNo = this.data.orderDetail.batchNo
        if (batchNo) {
          wx.get(`${wx.api.mallBatchOrder}?batchNo=${batchNo}`, res => {
            wx.hideLoading()
            console.log('==== batchOrder ===', res)
            if (res.code == 200) {
              this.setData({
                show3: true,
                batchShopList: res.data,
                batchType: '2'
              })
            }
          }, fail => {})
        } else {
          wx.get(`${wx.api.mallcancel}${e.currentTarget.dataset.id}`, res => {
            wx.hideLoading()
            console.log('==== deleteOrder ===', res)
            if (res.code == 200) {
              wx.showToast({
                icon: 'none',
                title: '暂无更多数据'
              })
              wx.setStorage({
                key: "shopListRefresh",
                data: 'true',
                success() {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })
            }
          }, fail => {})
        }
      })
      .catch(() => {
        // on cancel
      });
  },

  // 批量取消
  cancelOrderMore() {
    wx.get(`${wx.api.mallCancelMore}?batchNo=${this.data.orderDetail.batchNo}`, res => {
      wx.hideLoading()
      console.log('==== batchOrder ===', res)
      if (res.code == 200) {
        this.data.pageNum = 1
        this.setData({
          show3: false
        })
        wx.setStorage({
          key: "shopListRefresh",
          data: 'true',
          success() {
            wx.navigateBack({
              delta: 1
            })
          }
        })
      }
    }, fail => {})
  },

  // 确认收货
  confirmSign(e) {
    wx.get(`${wx.api.mallconfirmSign}${e.currentTarget.dataset.id}`, res => {
      console.log('==== deleteOrder ===', res)
      if (res.code == 200) {
        this.getDetail()
      }
    }, fail => {})
  },

  onClose1() {
    this.setData({
      show1: false
    });
  },

  onClose2() {
    this.setData({ show2: false });
  },
  
  onClose3() {
    this.setData({ show3: false });
  },

  imageLoad() {
    console.info('==== 图片加载完成 ====')
    wx.hideLoading()
  },

  // 保存图片
  save() {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getImageInfo({
      src: that.data.shareImg,
      success(ress) {
        console.log(ress)
        wx.saveImageToPhotosAlbum({
          filePath: ress.path,
          success(res) {
            wx.hideLoading()
            that.setData({
              show2: false
            })
            wx.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
  },

  //  获取分享文案
  getRisk() {
    wx.get('/api/config/configKey?key=share_rule', res => {
      if (res.code == 200) {
        this.setData({
          risk: res.msg.replace(/\\n/g, "\n")
        })
      }
    }, fail => {})
  },

  // 点击分享按钮
  toshare(e) {
    let that = this
    Dialog.confirm({
        title: '温馨提示',
        message: that.data.risk,
      })
      .then(() => {
        that.setData({
          show1: true
        });
      })
      .catch(() => {
        // on cancel
      });
  },

  // 分享
  share(e) {
    let api = '/api/orders/'
    if (e.currentTarget.dataset.type == 'link') {
      api += `shareUrl?goodsId=${this.data.orderDetail.orderGoods[0].goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}`
    } else if (e.currentTarget.dataset.type == 'link_wb') {
      api += `shareUrl?goodsId=${this.data.orderDetail.orderGoods[0].goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}&urlType=1`
    } else {
      api += `shareImage?goodsId=${this.data.orderDetail.orderGoods[0].goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}`
    }
    wx.get(api, res => {
      console.log(e.currentTarget.dataset.type, res)
      if (res.code == 200) {
        if (e.currentTarget.dataset.type == 'link' || e.currentTarget.dataset.type == 'link_wb') {
          wx.setClipboardData({
            data: res.data.shareUrl,
            success(_res) {
              wx.getClipboardData({
                success(__res) {
                  console.log(__res.data) // data
                }
              })
            }
          })
        } else {
          wx.showLoading({
            mask: true
          })
          this.setData({
            shareImg: res.data.shareImg,
            show2: true,
            show1: false
          })
        }
      }
    }, fail => {})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log(wx.getStorageSync('userInfo'))
    this.setData({
      userInfo: app.globalData.userInfo || wx.getStorageSync('userInfo')
    })
    this.getDetail()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.orderDetail.orderGoods[0].goodsName,
      path: `/pages/shopDetail/shopDetail?id=${this.data.orderDetail.orderGoods[0].goodsId}&userId=${this.data.userInfo.id}&grouponNo=${this.data.orderDetail.grouponNo}`,
      imageUrl: this.data.orderDetail.orderGoods[0].picUrl
    }
  }
})